package demo_JUC.base;


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

// 使用look锁的方式
public class SaleTicketDemo002 {
    public static void main(String[] args) {
        // 并发：多线程操作一个资源类，把资源类丢入线程
        Ticket ticket = new Ticket();

        new Thread(()->{
            for (int i=1;i<60;i++){ticket.sale();}
        }, "A").start();
        new Thread(()->{
            for (int i=1;i<60;i++){ticket.sale();}
        }, "B").start();
        new Thread(()->{
            for (int i=1;i<60;i++){ticket.sale();}
        }, "C").start();
    }
}

// 票：资源类：OOP
class Ticket002{
    private int number = 100; // 基本票数
    Lock lock = new ReentrantLock();
    // 卖票方法
    public void sale(){
        lock.lock(); // 加锁
        try {
            // 业务代码
            if (number> 0 ){
                System.out.println(Thread.currentThread().getName() + "卖出了" + (number--) + "票，剩余：" + number);
            }
        } finally {
            lock.unlock();
        }
    }
}